<template>
  <div>
    <el-dialog
      v-toggle-full
      v-loading.lock="loading"
      class="base-dialog storage-order-handle"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="title"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="innerDialogFormVisible"
      @closed="closeDialog"
    >
      <p slot="title">{{ title }}</p>
      <el-divider class="el-divider-specail" content-position="left"
        >入库单信息</el-divider
      >
      <el-form :model="detailData" status-icon label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库单编号">
              {{ orderNum }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              {{ createTime }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库仓库">
              {{ detailData.storageName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务类型">
              {{ detailData.orderTypeName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注">
              {{ detailData.remark }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理人">
              <el-select
                ref="selectDom"
                v-model="formData.disposePerson"
                :multiple-limit="2"
                multiple
                placeholder="请选择处理人"
                @change="disposePersonChange($event)"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        ref="table"
        :data="productList"
        fit
        highlight-current-row
        :header-cell-style="{ height: '50px' }"
        :cell-style="{ height: '50px' }"
        style="width: 100%; height: auto; overflow: auto"
      >
        <el-table-column label="危化品编号">
          <template slot-scope="scope">
            {{ scope.row.productNum }}
          </template>
        </el-table-column>
        <el-table-column label="危化品名称">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="型号规格">
          <template slot-scope="scope">
            {{ scope.row.specifications }}
          </template>
        </el-table-column>
        <el-table-column label="分类">
          <template slot-scope="scope">
            {{ scope.row.classOneName }}
          </template>
        </el-table-column>
        <el-table-column label="形态">
          <template slot-scope="scope">
            {{ scope.row.morphologyName }}
          </template>
        </el-table-column>
        <el-table-column label="存储条件">
          <template slot-scope="scope">
            {{ scope.row.storageConditionName }}
          </template>
        </el-table-column>
        <el-table-column label="包装单位">
          <template slot-scope="scope">
            {{ scope.row.unitName }}
          </template>
        </el-table-column>
        <el-table-column label="初始毛重（克）">
          <template slot-scope="scope">
            {{ scope.row.roughWeight }}
          </template>
        </el-table-column>
        <el-table-column label="生产商">
          <template slot-scope="scope">
            {{ scope.row.manufacturerName }}
          </template>
        </el-table-column>
        <el-table-column label="应收数量">
          <template slot-scope="scope">
            {{ scope.row.receiveAmount }}
          </template>
        </el-table-column>
      </el-table>
      <el-divider
        class="el-divider-specail el-divider-top"
        content-position="left"
      >
        <span class="title">入库明细列表</span>
        <div class="button-area">
          <div
            v-if="
              detailData.orderTypeCode === 100 ||
              detailData.orderTypeCode === 101
            "
          >
            <el-button type="primary" @click="preSetResidualWeight()"
              >批量设置重量</el-button
            >
            <el-button type="primary" @click="preSetDateManufacture()"
              >批量设置生产日期</el-button
            >
            <el-button type="primary" @click="preSetStorageArea()"
              >批量设置库区库位</el-button
            >
            <el-button type="primary" @click="toPrintBarcode()"
              >批量打印条形码</el-button
            >
          </div>
          <div v-if="detailData.orderTypeCode === 200">
            <el-input
              ref="txtSerialNum"
              v-model="serialNum"
              placeholder="请输入序列号/扫描条形码"
              autocomplete="off"
              style="width: 55%; float: left"
              @keyup.enter.native="addProductDetails"
            ></el-input>
            <el-button type="primary" @click="addProductDetails()"
              >添加</el-button
            >
            <el-tooltip
              class="item"
              effect="dark"
              content="文本框获得焦点后，扫描产品条形码"
              placement="right"
            >
              <el-button type="primary" @click="addProductByScanner()"
                >扫码添加</el-button
              >
            </el-tooltip>
          </div>
        </div>
      </el-divider>
      <el-form ref="formData" :model="formData" status-icon>
        <el-table
          v-if="formData.productDetails.length > 0"
          ref="table"
          v-loading="tableLoading"
          :data="formData.productDetails"
          highlight-current-row
          :header-cell-style="{ height: '50px' }"
          :cell-style="{ height: '70px', overflow: 'auto' }"
          style="width: 100%; height: auto; overflow: auto"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序列号" width="150">
            <template slot-scope="scope">
              {{ scope.row.serialNum }}
            </template>
          </el-table-column>
          <el-table-column label="危化品编号">
            <template slot-scope="scope">
              {{ scope.row.productNum }}
            </template>
          </el-table-column>
          <el-table-column label="条形码" width="280">
            <template slot-scope="scope">
              <JsBarcode :value="scope.row.serialNum" :valid="true"></JsBarcode>
            </template>
          </el-table-column>
          <el-table-column label="剩余重量（克）">
            <template slot-scope="scope">
              <el-form-item
                :key="scope.$index"
                :prop="'productDetails.' + scope.$index + '.residualWeight'"
                label-width="0px"
                :rules="[
                  {
                    required: !scope.row.isWaive,
                    message: '必填项',
                    trigger: 'change',
                  },
                  {
                    validator: Helper.validateFunctionPositiveFloatNumber,
                    trigger: 'change',
                  },
                ]"
              >
                <el-input
                  v-model="scope.row.residualWeight"
                  autocomplete="off"
                  type="number"
                  min="0"
                  placeholder="请输入"
                  :disabled="scope.row.isWaive === true"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="生产日期" width="150">
            <template slot-scope="scope">
              <el-form-item
                :key="scope.$index"
                :prop="'productDetails.' + scope.$index + '.dateManufacture'"
                label-width="0px"
                :rules="[
                  {
                    required: !scope.row.isWaive,
                    message: '必填项',
                    trigger: 'change',
                  },
                ]"
              >
                <el-date-picker
                  v-model="scope.row.dateManufacture"
                  type="date"
                  placeholder="请选择"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :disabled="
                    scope.row.isWaive === true ||
                    detailData.orderTypeCode === 200
                  "
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="库区">
            <template slot-scope="scope">
              <el-form-item
                :key="scope.$index"
                :prop="'productDetails.' + scope.$index + '.storageAreaId'"
                label-width="0px"
                :rules="[
                  {
                    required: !scope.row.isWaive,
                    message: '必填项',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select
                  v-model="scope.row.storageAreaId"
                  filterable
                  placeholder="库区"
                  :disabled="scope.row.isWaive === true"
                  @change="
                    selectStorageArea(scope.row.storageAreaId, scope.$index)
                  "
                >
                  <el-option
                    v-for="item in scope.row.storageAreaOptions"
                    :key="item.value"
                    :label="item.areaName"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="库位">
            <template slot-scope="scope">
              <el-form-item
                :key="scope.$index"
                :prop="'productDetails.' + scope.$index + '.storageSpaceId'"
                label-width="0px"
                :rules="[
                  {
                    required: !scope.row.isWaive,
                    message: '必填项',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select
                  v-model="scope.row.storageSpaceId"
                  filterable
                  placeholder="库位"
                  :disabled="scope.row.isWaive === true"
                >
                  <el-option
                    v-for="item in scope.row.storageSpaceOptions"
                    :key="item.value"
                    :label="item.number"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="放弃入库" width="80">
            <template slot-scope="scope">
              <el-checkbox
                v-model="scope.row.isWaive"
                @change="selectIsWaive(scope.row, scope.$index)"
              ></el-checkbox>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')"
          >处理完成</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <StorageOrderResidualWeight
      v-if="dialogResidualWeightVisible"
      ref="StorageOrderResidualWeight"
      :dialog-residual-weight-visible.sync="dialogResidualWeightVisible"
      @batchSetResidualWeight="batchSetResidualWeight"
    />
    <StorageOrderDateManufacture
      v-if="dialogDateManufactureVisible"
      ref="StorageOrderDateManufacture"
      :dialog-date-manufacture-visible.sync="dialogDateManufactureVisible"
      @batchSetDateManufacture="batchSetDateManufacture"
    />
    <DialogStorageArea
      v-if="dialogStorageAreaVisible"
      ref="DialogStorageArea"
      :storage-id.sync="detailData.storageId"
      :dialog-storage-area-visible.sync="dialogStorageAreaVisible"
      @batchSetStorageArea="batchSetStorageArea"
    />
    <!-- 打印标签 -->
    <div
      id="printDiv"
      ref="printDiv"
      style="display: none; width: 60mm; height: 40mm"
    >
      <div
        v-for="item in selectionTables"
        :key="item.serialNum"
        style="
          page-break-after: always;
          vertical-align: middle;
          text-align: center;
          height: 70px;
        "
      >
        <img
          :src="item.serialNum | creatBarCode(item.serialNum)"
          style="max-width: 100%; max-height: 100%"
        />
      </div>
    </div>
    <iframe
      ref="printIframe"
      frameborder="0"
      scrolling="no"
      style="margin: 0px; padding: 0px; width: 0px; height: 0px"
    ></iframe>
  </div>
</template>

<script>
import {
  getInfo,
  getStorageProductStoreDetailsList,
  getStorageAreaList,
  getStorageSpaceList,
  completeOrder,
  GetWarehouseKeeper,
} from "../../../../api/Storage/StorageOrderIn.js";
import JsBarcode from "../../../../components/JsBarcode.vue";
import BarcodeJs from "jsbarcode";
import StorageOrderResidualWeight from "./StorageOrderResidualWeight.vue";
import StorageOrderDateManufacture from "./StorageOrderDateManufacture.vue";
import DialogStorageArea from "./DialogStorageArea.vue";
import { MessageBox } from "element-ui";
export default {
  name: "StorageOrderInHandle",
  components: {
    JsBarcode,
    StorageOrderResidualWeight,
    StorageOrderDateManufacture,
    DialogStorageArea,
  },
  filters: {
    creatBarCode(barCodeData) {
      console.log("触发条码生成事件");
      const canvas = document.createElement("canvas");
      BarcodeJs(canvas, barCodeData, {
        format: "CODE128",
        displayValue: true,
        height: 40,
        width: 2,
        textAlign: "center",
        font: "cursive",
        fontOptions: "bold",
        fontSize: 20,
        textMargin: 5,
      });
      return canvas.toDataURL("image/png");
    },
  },
  props: {
    dialogHandleVisible: {
      type: Boolean,
      default: false,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: "",
    },
    orderNum: {
      type: String,
      default: "",
    },
    createTime: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      userList: [],
      searchUserLoading: false,
      title: "处理入库单信息",
      loading: false,
      tableLoading: false,
      innerDialogFormVisible: false,
      dialogResidualWeightVisible: false,
      dialogDateManufactureVisible: false,
      dialogStorageAreaVisible: false,
      detailData: {},
      productList: [],
      formData: {
        disposePersonId: "",
        disposePersonName: "",
        disposePerson: [],
        productDetails: [],
      },
      serialNum: "",
      storageAreaOptions: [],
      storageSpaceOptions: [],
      selectionTables: [],
    };
  },
  watch: {},
  created() {
    this.innerDialogFormVisible = this.dialogHandleVisible;
    this.init();
    const _this = this;
    setTimeout(function() {
      const input = _this.$refs["txtSerialNum"];
      if (input) {
        input.focus();
      }
    }, 500);
  },
  deactivated() {
    var printIframe = this.$refs.printIframe;
    var html = this.$refs.printDiv.innerHTML;
    printIframe.setAttribute("srcdoc", html);
    printIframe.onload = function() {
      printIframe.contentWindow.focus();
      printIframe.contentWindow.close();
    };
  },
  methods: {
    async init() {
      if (this.editId) {
        await this.getDetail();
      }
    },
    handleSelectionChange(val) {
      this.selectionTables = val;
      console.log(this.selectionTables);
    },
    addProductByScanner() {
      this.serialNum = "";
      this.$refs["txtSerialNum"].focus();
    },
    // 归还入库新增
    addProductDetails() {
      getStorageProductStoreDetailsList({
        storageId: this.detailData.storageId,
        serialNum: this.serialNum,
        orderId: this.detailData.id,
        status: 300, // 归还入库  可用状态
        pageIndex: 1,
        pageSize: 50000,
      }).then((res) => {
        if (res.data?.length > 0) {
          const productDetails = res.data.map((item, index) => {
            this.getStorageSpaceList(item.storageAreaId, index);
            return {
              ...item,
              storageAreaId: {
                value: item.storageAreaId,
                areaName: item.storageAreaName,
              },
              storageSpaceId: {
                value: item.storageSpaceId,
                number: item.storageSpaceName,
              },
              storageAreaOptions: this.storageAreaOptions,
              storageSpaceOptions: this.storageSpaceOptions,
            };
          });
          this.formData.productDetails =
            this.formData.productDetails.concat(productDetails);
          this.formData.productDetails = this.unique(
            this.formData.productDetails,
            "serialNum"
          );
          console.log(this.formData.productDetails);
        }
        this.serialNum = "";
        this.$refs["txtSerialNum"].focus();
      });
    },
    unique(arr, u_key) {
      const map = new Map();
      arr.forEach((item, index) => {
        if (!map.has(item[u_key])) {
          map.set(item[u_key], item);
        }
      });
      return [...map.values()];
    },
    // 批量设置重量
    preSetResidualWeight() {
      if (this.selectionTables.length <= 0) {
        this.$message.error("请勾选入库明细");
        return;
      }
      this.dialogResidualWeightVisible = true;
    },
    batchSetResidualWeight(formData) {
      const { residualWeight } = formData;
      this.selectionTables.forEach(item => {
        this.formData.productDetails.map(it => {
          if (it.id === item.id) {
            it.residualWeight = residualWeight;
          }
        });
      });
    },

    // 批量设置生产日期
    preSetDateManufacture() {
      if (this.selectionTables.length <= 0) {
        this.$message.error("请勾选入库明细");
        return;
      }
      this.dialogDateManufactureVisible = true;
    },
    batchSetDateManufacture(formData) {
      const { dateManufacture } = formData;
      this.selectionTables.forEach(item => {
        this.formData.productDetails.map(it => {
          if (it.id === item.id) {
            it.dateManufacture = dateManufacture;
          }
        });
      });
    },

    // 批量设置库区库位
    preSetStorageArea() {
      if (this.selectionTables.length <= 0) {
        this.$message.error("请勾选入库明细");
        return;
      }
      this.dialogStorageAreaVisible = true;
    },
    batchSetStorageArea(formData) {
      const { storageAreaId, storageSpaceId, storageSpaceOptions } = formData;
      this.storageSpaceOptions = storageSpaceOptions;
      this.selectionTables.forEach(item => {
        this.formData.productDetails.map(it => {
          if (it.id === item.id) {
            it.storageAreaId = storageAreaId;
            it.storageSpaceId = storageSpaceId;
            it.storageSpaceOptions = storageSpaceOptions;
          }
        });
      });
    },

    // 是否放弃入库
    selectIsWaive(row, index) {
      // if (row.isWaive) {
      //   this.formData.productDetails[index].residualWeight = ''
      //   this.formData.productDetails[index].dateManufacture = ''
      //   this.formData.productDetails[index].storageAreaId = ''
      //   this.formData.productDetails[index].storageSpaceId = ''
      // }
      console.log(row);
    },
    // 获取库区下拉框
    getStorageAreaList() {
      getStorageAreaList({
        storageId: this.detailData.storageId,
        status: 1,
        pageIndex: 1,
        pageSize: 50000,
      }).then((res) => {
        if (res.data.dataList?.length > 0) {
          this.storageAreaOptions = res.data.dataList.map((item) => {
            return {
              ...item,
              value: item.id,
            };
          });
        } else {
          this.storageAreaOptions = [];
        }
        this.formData.productDetails = this.formData.productDetails.map(
          (item) => {
            return {
              ...item,
              storageAreaOptions: this.storageAreaOptions,
              storageSpaceOptions: this.storageSpaceOptions,
            };
          }
        );
      });
    },
    // 选择库位下拉框
    selectStorageArea(item, index) {
      this.formData.productDetails[index].storageSpaceId = "";
      this.getStorageSpaceList(item.value, index);
    },
    getStorageSpaceList(storageAreaId, index) {
      getStorageSpaceList({
        storageId: this.detailData.storageId,
        storageAreaId: storageAreaId,
        status: 1,
        pageIndex: 1,
        pageSize: 50000,
      }).then((res) => {
        if (res.data.dataList?.length > 0) {
          this.storageSpaceOptions = res.data.dataList.map((item) => {
            return {
              ...item,
              value: item.id,
            };
          });
        } else {
          this.storageSpaceOptions = [];
        }
        if (index !== "") {
          this.formData.productDetails[index].storageSpaceOptions =
            this.storageSpaceOptions;
        }
      });
    },
    // 获取详情
    getDetail() {
      this.loading = true;
      getInfo({ id: this.editId })
        .then((res) => {
          this.loading = false;
          this.detailData = res.data;
          this.productList = res.data.product;
          console.log(this.productList);
          if (res.data.productDetails?.length > 0) {
            this.formData.productDetails = res.data.productDetails.map(
              (item) => {
                return {
                  ...item,
                  storageAreaId: "",
                  storageSpaceId: "",
                  storageAreaOptions: [],
                  storageSpaceOptions: [],
                };
              }
            );
          }
          this.getDisposePersonList("", this.detailData.storageId);
          this.getStorageAreaList();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 处理人下拉列表
    getDisposePersonList(name = "", storageId = 0) {
      GetWarehouseKeeper({ name: name, storageId: storageId }).then((res) => {
        this.userList = res.data;
      });
    },
    disposePersonChange(val) {
      this.formData.disposePerson = [];
      var idArr = [];
      var nameArr = [];
      for (let i = 0; i < val.length; i++) {
        this.userList.find(item => {
          if (item.id === val[i]) {
            idArr.push(item.id);
            nameArr.push(item.name);
            this.formData.disposePerson.push(item.id);
          }
        });
      }
      this.formData.disposePersonId = idArr.join(",");
      this.formData.disposePersonName = nameArr.join(",");
    },
    cancel() {
      this.innerDialogFormVisible = false;
      this.$emit("update:dialogHandleVisible", false);
      this.$emit("update:editId", "");
      this.$parent.getList();
    },
    closeDialog() {
      this.cancel();
    },
    onSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (this.formData.disposePerson.length < 2) {
            this.$message.error("请选择两位处理人");
            return false;
          }
          this.loading = true;
          const orderProductDetails = this.formData.productDetails.map(
            (item) => {
              return {
                id: item.id,
                residualWeight: item.residualWeight,
                storageAreaName: item.storageAreaId.areaName,
                storageAreaId: item.storageAreaId.value,
                storageSpaceId: item.storageSpaceId.value,
                storageSpaceName: item.storageSpaceId.number,
                isWaive: item.isWaive ? 1 : 0,
                dateManufacture: item.dateManufacture,
                productId: item.productId,
                productNum: item.productNum,
                serialNum: item.serialNum,
              };
            }
          );
          completeOrder({
            orderId: this.detailData.id,
            orderProductDetails: orderProductDetails,
            disposePersonId: this.formData.disposePersonId,
            disposePersonName: this.formData.disposePersonName,
          }).then((res) => {
            this.loading = false;
            if (res.code === 200 && res.data) {
              MessageBox.confirm(res.msg, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                center: true,
              }).then(() => {
                completeOrder({
                  disposePersonId: this.formData.disposePersonId,
                  disposePersonName: this.formData.disposePersonName,
                  orderId: this.detailData.id,
                  isForcedSubmission: true,
                  orderProductDetails: orderProductDetails,
                }).then((res) => {
                  this.closeDialog();
                });
              }).catch((action) => { });
            } else {
              this.closeDialog();
            }
          }).catch(() => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    // 标签打印
    toPrintBarcode() {
      if (this.selectionTables.length <= 0) {
        this.$message.error("请勾选需要打印的条形码");
        return;
      }
      var printIframe = this.$refs.printIframe;
      var html = this.$refs.printDiv.innerHTML;
      printIframe.setAttribute("srcdoc", html);
      printIframe.onload = function() {
        console.log(printIframe.contentWindow);
        // 去掉iframe里面的dom的body的padding margin的默认数值
        printIframe.contentWindow.document.body.style.padding = "0px";
        printIframe.contentWindow.document.body.style.margin = "0px";
        // 开始打印
        printIframe.contentWindow.focus();
        printIframe.contentWindow.print();
      };
    },
  },
};
</script>
<style lang="scss">
.storage-order-handle {
  margin-top: 10px;
  width: 100%;

  .el-dialog__footer .el-button {
    width: 90px;
  }

  .el-table .cell {
    overflow: visible;
  }

  .el-form {
    border: 1px solid #e6ebf5;

    .el-row {
      border-bottom: 1px solid #e6ebf5;

      &:last-child {
        border-bottom: none;
      }

      .el-col {
        &:nth-child(2n + 1) {
          .el-form-item {
            .el-form-item__label {
              border-left: none;
            }
          }
        }

        .el-form-item {
          margin: 0;
          height: 40px;
          line-height: 40px;

          .el-form-item__label {
            height: 100%;
            line-height: 40px;
            background: #f1f8ff;
            border-left: 1px solid #e6ebf5;
            border-right: 1px solid #e6ebf5;
            text-align: center;
            color: #909399;
            font-weight: bold;
          }

          .el-form-item__content {
            text-align: left;
            height: 100%;
            line-height: 40px;
            margin-left: 20px;
          }
        }
      }
    }
  }

  .title {
    display: inline-block;
    vertical-align: middle;
  }

  .el-divider-specail {
    background: transparent;

    .el-divider__text {
      font-weight: bold;
      font-size: 15px;
      left: -20px;
    }

    &.el-divider-top {
      margin-top: 60px;
    }
  }

  .button-area {
    display: inline-block;
    vertical-align: middle;
    margin-left: 20px;
  }
}
</style>
